package com.example.oauth2.config.oauth2;


import com.alibaba.fastjson.JSON;
import com.example.oauth2.common.result.Result;
import com.example.oauth2.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description： 拦截器 -- oauth验权
 * @author: xuwenqian
 * @date: 2020/4/15 15:18
 */
@Slf4j
@Component
public class Oauth2Interceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private TokenStore tokenStore;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return resultMessage(response, Result.fail(ResultCode.HEADER_INVALID.code, ResultCode.HEADER_INVALID.msg));
        }

        OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(authorization.split(" ")[0]);
        if (oAuth2AccessToken != null) {
            tokenStore.removeAccessToken(oAuth2AccessToken);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    public Boolean resultMessage(HttpServletResponse response, Result result) {
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try (ServletOutputStream writer = response.getOutputStream()) {
            writer.write(JSON.toJSONBytes(result));
        } catch (IOException e) {
            log.error("response error", e);
        }
        return false;
    }

}
